package com.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class ServerSocketChannelDemo {


    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 8888;
        ByteBuffer buffer = ByteBuffer.wrap("123".getBytes(StandardCharsets.UTF_8));
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //绑定
        ssc.socket().bind(new InetSocketAddress(port));
        ssc.configureBlocking(false);
        //监听是否有新的连接传入
        while (true) {
            System.out.println("wait connect");
            SocketChannel accept = ssc.accept();
            if (accept == null) {
                System.out.println("null");
                Thread.sleep(2000);
            } else {
                buffer.rewind();
                //访问127.0.0.1:8888时，会有响应
                System.out.println("not null" + accept.socket().getRemoteSocketAddress());
                //指针0
                accept.write(buffer);
                accept.close();
            }
        }
    }
}

// tcp
class SocketChannelDemo {
    public static void main(String[] args) throws IOException {
        //创建SocketChannel 2种方法
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("", 80));
        // SocketChannel open1 = SocketChannel.open();
        // open1.connect(new InetSocketAddress("", 80));
        socketChannel.configureBlocking(false);
        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //读取数据到buffer
        int read = socketChannel.read(buffer);

    }
}

